<template>
  <div class="hello">
    <!-- 首页
    <button @click="jump">跳转</button> -->
    <div style="position: relative">
      <van-image width="100%" fit="contain" :src="Background" />
      <div style="position: absolute; top: 10px; right: 10px; cursor: pointer">
        <span style="margin-left: 5px; color: white" @click="switchUser"
          >切换用户</span
        >
        <div>
          <!-- 下拉选择器 -->
          <van-popup v-model="userPop" position="bottom" style="height: 60%">
            <div style="display: flex; flex-direction: column; height: 100%">
              <!-- 固定顶部搜索框 -->
              <div style="flex-shrink: 0; background: white; z-index: 1">
                <van-search
                  v-model="searchValue"
                  placeholder="请输入搜索内容"
                  @input="handleSearch"
                  style="padding: 10px 16px"
                />
              </div>
              <!-- 可滑动内容区域 -->
              <van-picker
                :columns="filteredOptions"
                style="flex-grow: 1; overflow-y: auto"
                :show-toolbar="false"
                @change="handleChange"
                ref="pickerUser"
              />
              <!-- 固定底部按钮 -->
              <div
                style="
                  flex-shrink: 0;
                  display: flex;
                  justify-content: space-between;
                  padding: 16px;
                  border-top: 1px solid #ebedf0;
                  background: white;
                "
              >
                <van-button @click="backUser" style="width: 45%"
                  >切回</van-button
                >
                <van-button
                  @click="handleConfirm"
                  type="primary"
                  style="width: 45%"
                  >确定</van-button
                >
              </div>
            </div>
          </van-popup>
        </div>
      </div>
    </div>
    <van-tabs v-model="homeTabActive" color="rgb(78,119,165)">
      <van-tab v-for="(item, index) in menuList" :key="index" style="">
        <template #title>
          {{ item.name }}
        </template>
        <div class="center" style="flex-wrap: wrap; display: flex; padding: 5%">
          <div
            v-for="(list, index) in item.list"
            :key="'list' + index"
            class="list"
            @click="jump(list)"
            :style="
              item.list ? (item.list.length <= 1 ? 'border:none' : '') : ''
            "
          >
            <span class="iconfont icon-xxx"></span>
            <van-image
              width="2rem"
              height="2rem"
              fit="contain"
              :src="ka1"
              style="margin: 0 4%"
            />
            <span>{{ list.name }}</span>
          </div>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>
<script>
import Background from "@/assets/img/background.png";
import ka1 from "@/assets/iconfont/卡1.png";
import { pageSearch, getGoldenServiceRole, getStaffById } from "@/api/apis";
import user from "@/api/user";
import { listMenus } from "@/utils/listMenus";
import { mapState, mapMutations } from "vuex";
import store from "@/store";
export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  data() {
    return {
      Background: Background,
      ka1: ka1,
      active: 0,
      pageSize: "3600",
      current: "0", // 每页显示的数量
      userPop: false,
      searchValue: "", // 搜索框的值
      searchStaffId: "", // 搜索框stuffId的值
      filteredOptions: [], // 过滤后的选项
      menus:
        localStorage.getItem("menu") &&
        localStorage.getItem("menu") !== "undefined" &&
        localStorage.getItem("menu") !== "null"
          ? JSON.parse(localStorage.getItem("menu"))
          : [], // 菜单数据
      dataList: [
        {
          name: "首页",
          type: "0",
          list: [
            {
              name: "公告",
              path: "/notice",
            },
          ],
        },
        {
          name: "申请服务",
          type: "1",
          list: [],
        },
        {
          name: "审批",
          type: "2",
          list: [],
        },
        {
          name: "查询",
          type: "3",
          list: [],
        },
      ],
      headers: {
        // 'initialValue': Cookies.get('Authorization')
        initialValue: localStorage.getItem("initialValue"),
      },
    };
  },
  created() {},
  mounted() {
    if (
      !this.$store.state.userInfo.staff ||
      !localStorage.getItem("menu") ||
      !localStorage.getItem("tokenValue")
    ) {
      this.autoLogin(); // 如果不存在，执行 autoLogin
    }
  },
  computed: {
    homeTabActive: {
      get() {
        return this.$store.state.homeTabActive;
      },
      set(value) {
        this.setHomeTabActive(value); // 使用 mapMutations 中的方法
      },
    }, // 获取 homeTabActive
    menuList: {
      get() {
        return this.$store.state.menuList;
      },
      set(value) {
        this.updateMenuList(value); // 使用 mapMutations 中的方法
      },
    }, // 获取 meunList
  },
  methods: {
    ...mapMutations(["setHomeTabActive","updateMenuList"]), // 获取 setHomeTabActive mutation
    handleSearch() {
      if (this.searchValue) {
        const params = {
          // page: {
          //   size: this.pageSize,
          //   current: this.page,
          // },
          realNameLikeList: [this.searchValue],
        };
        pageSearch(params).then((res) => {
          const names = res.data.records.map((item) => {
            return {
              text: item.realName + " (" + item.mobile + ")",
              value: item.id, // 假设每个选项都有一个唯一的id属性
            };
          });
          this.filteredOptions = names;
        });
      }
    },
    getPickerUserValue() {
      if (this.$refs.pickerUser) {
        const selectedValue = this.$refs.pickerUser.getValues()[0]; // 获取选中的值
        this.searchValue = selectedValue.text; // 获取显示的文本吧
        this.searchStaffId = selectedValue.value; // 获取对应的值
      } else {
        console.log("pickerUser 未找到 >");
      }
    },
    handleChange() {
      this.getPickerUserValue();
      this.userPop = false;
    },
    // 处理选择确认
    handleConfirm() {
      this.getPickerUserValue();
      this.userPop = false;
      user
        .changeStaffLogin({ changeToStaffId: this.searchStaffId }, this.headers)
        .then((res) => {
          localStorage.setItem("tokenValue", res.changeStaffToken);
          localStorage.removeItem("roleRefresh");
          this.autoLogin();
          window.location.reload();
        });
    },
    backUser() {
      this.userPop = false;
      localStorage.setItem("tokenValue", localStorage.getItem("initialValue"));
      window.location.reload();
    },
    switchUser() {
      this.userPop = true;
    },
    closeUserPopup() {
      this.userPop = false;
    },
    jump(item) {
      this.active = item.type;
      this.$router.push({
        path: item.path,
        query: {
          itemTitle: item.title,
        },
      });
    },
    autoLogin(data) {
      const tokenValue = localStorage.getItem("tokenValue");
      if (!tokenValue) {
        const ref = window.location.href;
        console.log("window.location.href", window.location.href);
        const url = process.env.VUE_APP_LOGIN_URL + "/#/login?url=" + ref;
        console.log("url", url);
        window.location.href = url;
      }
      if (
        localStorage.getItem("tokenValue") &&
        localStorage.getItem("tokenValue") != "undefined"
      ) {
        getGoldenServiceRole().then((res) => {
          getStaffById().then((r) => {
            if (r.success) {
              localStorage.setItem("staffId", r.data.id);
              localStorage.setItem("realName", r.data.realName);
              this.$store.commit("setUserInfo", {
                staff: r.data.id,
                realName: r.data.realName,
              });
              this.realName = localStorage.getItem("realName");
            }
          });
          if (res.success) {
            if (!localStorage.getItem("roleRefresh")) {
              localStorage.setItem("roleRefresh", "true");
              localStorage.setItem("role", JSON.stringify(res.data));
              window.location.reload();
            }
            listMenus(res.data).then((res) => {
              localStorage.setItem("menu", JSON.stringify(res));
              // 菜单比对方法
              this.meunesControl(JSON.stringify(res));
              this.menus = JSON.parse(localStorage.getItem("menu"));
              console.log("this.menus", this.menus);
            });
          }
        });
      } else {
        Message.error(localStorage.getItem("tokenValue"));
      }
    },
    changeToArray(list) {
      if (Object.prototype.toString.call(list) !== "[object Array]") {
        return JSON.parse(list);
      }
    },
    // 权限菜单控制
    meunesControl(list) {
      const arr = [        {
          name: "首页",
          type: "0",
          list: [
            {
              name: "公告",
              path: "/notice",
            },
          ],
        },
        {
          name: "申请服务",
          type: "1",
          list: [],
        },
        {
          name: "审批",
          type: "2",
          list: [],
        },
        {
          name: "查询",
          type: "3",
          list: [],
        },]
      this.updateMenuList(arr);
      const result = this.changeToArray(list);
      result.forEach((item) => {
        if (item.type == "0") {
          this.dataList[0].list.push(item);
        }
        if (item.type == "1") {
          this.dataList[1].list.push(item);
        }
        if (item.type == "2") {
          this.dataList[2].list.push(item);
        }
        if (item.type == "3") {
          this.dataList[3].list.push(item);
        }
      });
      this.updateMenuList(this.dataList);
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
.center .list:nth-of-type(2n + 1) {
  border-right: 1px solid #eee;
}
.center .list:nth-child(4n + 1),
.center .list:nth-child(4n + 2) {
  border-bottom: 1px solid #eee;
}
.list {
  width: 43%;
  /* border:1px solid red; */
  display: flex;
  align-items: center;
  padding: 3%;
}
</style>
